package org.springframework.security.web.authentication.rememberme;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.mongodb.BasicDBObject;
import com.nuanshui.heatedloan.baseservice.model.UserAgent;
import com.nuanshui.heatedloan.model.UserOprationRecord;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.framework.utils.mongo.MongoManager;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.userinfo.facade.UserTokenService;
import com.nuanshui.heatedloan.userinfo.model.User;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 
 * @ClassName: AuthenticationSuccessHandlerImpl
 * @author guohao
 * @date 2015年4月15日 下午2:52:40
 *
 */
public class AuthenticationSuccessHandlerImpl implements
		AuthenticationSuccessHandler {

	
	private Logger logger  = LoggerFactory.getLogger(AuthenticationSuccessHandlerImpl.class);
	@Reference(url=GlobalParam.USER_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
	private UserTokenService userTokenService;
	@Autowired
	private MongoManager mongoManager;
	
	@Override
	public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
			HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {
		
		try {
			LogUtil.info(logger, "--------------------获取参数-----------------");
			UserAgent userAgent =  (UserAgent) httpServletRequest.getAttribute(GlobalParam.USER_AGENT);
			String deviceType = httpServletRequest.getParameter("deviceType");
			if(StringUtils.isEmpty(deviceType)){
				deviceType = userAgent.getClient();
			}
			String version = httpServletRequest.getParameter("version");
			if(StringUtils.isEmpty(version)){
				version = userAgent.getVersion();
			}
			String deviceToken = httpServletRequest.getParameter("deviceToken");// 用户传进来的token
			if(StringUtils.isEmpty(deviceToken)){
				deviceToken = userAgent.getDeviceToken();
			}
			
			String userId = null;
			Authentication auth = SecurityContextHolder.getContext().getAuthentication();
			Object principal = auth.getPrincipal();
			if (principal != null && principal instanceof User) {
				User user = (User) principal;
				userId = user.getId();
				user.getPhone();
			}
			LogUtil.info(logger, "deviceType :" + deviceType);
			LogUtil.info(logger, "version :" + version);
			LogUtil.info(logger, "deviceToken :" + deviceToken);
			LogUtil.info(logger, "userId :" + userId);
			LogUtil.info(logger, "-------------------------------------");
			//添加userToken
			userTokenService.addUserTokenOnAsyn(deviceToken, deviceType, version, userId);
			
			//记录登录详情到MONGODB
			UserOprationRecord uor = new UserOprationRecord();
			uor.setUserId(userId);
			SimpleDateFormat  sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			uor.setOpTime(  sdf.format(  new  Date()));
			uor.setOpType("登录");
			uor.setChannel(userAgent.getClient());
			uor.setIpAddress (httpServletRequest.getRemoteAddr());
			uor.setSafeToken(userAgent.getSafeToken());
			BasicDBObject basicDBObject = new BasicDBObject(JSON.parseObject(JSON.toJSONString(uor)));
			mongoManager.save(UserOprationRecord.USER_OPRATION_RECORD, basicDBObject);
		} catch (Exception e) {
			LogUtil.error(logger, "登录有问题",e);
		}	
		//indexMenuService.syncMenu(httpServletRequest);
		response.sendRedirect("/signined");
	}
}